﻿using System;
using System.IO;
using System.Xml;

namespace Common.DBUtility
{
    /// <summary>
    /// FileDirectoryUtility 类,方法不包含异常处理
    /// </summary>
    public class FileHelper
    {
        #region 初始化
        public static string BaseDir = System.Configuration.ConfigurationManager.AppSettings["basedir"];
        #endregion

        /// <summary>
        /// 路径分割符
        /// </summary>
        private const string PATH_SPLIT_CHAR = "\\";
        /// <summary>
        /// 指定文件上传路径如果不存在就创建它
        /// </summary>
        /// <param name="path"></param>
        public static void IsExits(string path)
        {
            string[] paths = path.Split(char.Parse(PATH_SPLIT_CHAR));
            string temppath ="";
            foreach (string str in paths)
            {
                temppath = temppath + str + @"\";
                if (!Directory.Exists(temppath))
                {
                    CreateDirectory(temppath);
                }
            }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        private FileHelper()
        {
        }
        /// <summary>
        /// 指定文件是否存在
        /// </summary>
        /// <param name="path"></param>
        public static bool FileExits(string path)
        {
            if (string.IsNullOrEmpty(path))
                return false;
            string Sitedir = FileHelper.GetBaseDir();//网站根目录
            path = Sitedir + path;
            path = path.Replace("/", @"\").Replace(@"\\", @"\");
            if (File.Exists(path))
                return true;
            else
                return false;
        }
        /// <summary>
        /// 复制指定目录的所有文件,不包含子目录及子目录中的文件
        /// </summary>
        /// <param name="sourceDir">原始目录</param>
        /// <param name="targetDir">目标目录</param>
        /// <param name="overWrite">如果为true,表示覆盖同名文件,否则不覆盖</param>
        public static void CopyFiles(string sourceDir, string targetDir, bool overWrite)
        {
            if (Directory.Exists(sourceDir) && Directory.Exists(targetDir))
            {
                 CopyFiles(sourceDir, targetDir, overWrite, false);
            }
        }
        /// <summary>
        /// 复制指定目录的所有文件
        /// </summary>
        /// <param name="sourceDir">原始目录</param>
        /// <param name="targetDir">目标目录</param>
        /// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
        /// <param name="copySubDir">如果为true,包含目录,否则不包含</param>
        public static void CopyFiles(string sourceDir, string targetDir, bool overWrite, bool copySubDir)
        {
            //复制当前目录文件
            try
            {
                foreach (string sourceFileName in Directory.GetFiles(sourceDir))
                {
                    string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf(PATH_SPLIT_CHAR) + 1));

                    if (File.Exists(targetFileName))
                    {
                        if (overWrite == true)
                        {
                            File.SetAttributes(targetFileName, FileAttributes.Normal);
                            File.Copy(sourceFileName, targetFileName, overWrite);
                        }
                    }
                    else
                    {
                        File.Copy(sourceFileName, targetFileName, overWrite);
                    }
                }
                //复制子目录
                if (copySubDir)
                {
                    foreach (string sourceSubDir in Directory.GetDirectories(sourceDir))
                    {
                        string targetSubDir = Path.Combine(targetDir, sourceSubDir.Substring(sourceSubDir.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                        if (!Directory.Exists(targetSubDir))
                            Directory.CreateDirectory(targetSubDir);
                        CopyFiles(sourceSubDir, targetSubDir, overWrite, true);
                    }
                }
            }
            catch (Exception ex)
            {
                throw(ex);
            }
        }
        /// <summary>
        /// 剪切指定文件
        /// </summary>
        /// <param name="sourceFileName">原始地址</param>
        /// <param name="targetFileName">目标地址</param>
        /// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
        public static void MoveFile(string sourceFileName, string targetFileName, bool overWrite)
        {
            try
            {
                string Sitedir = BaseDir;//网站根目录
                sourceFileName = Sitedir + sourceFileName;
                sourceFileName = sourceFileName.Replace("/", @"\").Replace(@"\\", @"\");
                targetFileName = Sitedir + targetFileName;
                targetFileName = targetFileName.Replace("/", @"\").Replace(@"\\", @"\");
                if (!File.Exists(sourceFileName))
                    return;
                File.Move(sourceFileName, targetFileName);
            }
            catch(Exception ex)
            {
                throw (ex);
            }
        }
        /// <summary>
        /// 剪切指定目录的所有文件,不包含子目录
        /// </summary>
        /// <param name="sourceDir">原始目录</param>
        /// <param name="targetDir">目标目录</param>
        /// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
        public static void MoveFiles(string sourceDir, string targetDir, bool overWrite)
        {
            MoveFiles(sourceDir, targetDir, overWrite, false);
        }
        /// <summary>
        /// 剪切指定目录的所有文件
        /// </summary>
        /// <param name="sourceDir">原始目录</param>
        /// <param name="targetDir">目标目录</param>
        /// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
        /// <param name="moveSubDir">如果为true,包含目录,否则不包含</param>
        public static void MoveFiles(string sourceDir, string targetDir, bool overWrite, bool moveSubDir)
        {
            string Sitedir = BaseDir;//网站根目录
            sourceDir = Sitedir + sourceDir;
            sourceDir = sourceDir.Replace("/", @"\").Replace(@"\\", @"\");
            targetDir = Sitedir + targetDir;
            targetDir = targetDir.Replace("/", @"\").Replace(@"\\", @"\");
            if (!File.Exists(sourceDir))
            return;
            //移动当前目录文件
            foreach (string sourceFileName in Directory.GetFiles(sourceDir))
            {
                string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                if (File.Exists(targetFileName))
                {
                    if (overWrite == true)
                    {
                        File.SetAttributes(targetFileName, FileAttributes.Normal);
                        File.Delete(targetFileName);
                        File.Move(sourceFileName, targetFileName);
                    }
                }
                else
                {
                    File.Move(sourceFileName, targetFileName);
                }
            }
            if (moveSubDir)
            {
                foreach (string sourceSubDir in Directory.GetDirectories(sourceDir))
                {
                    string targetSubDir = Path.Combine(targetDir, sourceSubDir.Substring(sourceSubDir.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                    if (!Directory.Exists(targetSubDir))
                        Directory.CreateDirectory(targetSubDir);
                    MoveFiles(sourceSubDir, targetSubDir, overWrite, true);
                    Directory.Delete(sourceSubDir);
                }
            }
        }

        /// <summary>
        /// 删除指定目录的所有文件，不包含子目录
        /// </summary>
        /// <param name="targetDir">操作目录</param>
        public static void DeleteFiles(string targetDir)
        {
            string Sitedir = BaseDir;//网站根目录
            targetDir = Sitedir + targetDir;
            targetDir = targetDir.Replace("/",@"\");
            DeleteFiles(targetDir, false);
        }
        /// <summary>
        /// 删除指定路径的文件
        /// </summary>
        /// <param name="filepath"></param>
        public static void delfile(string filepath)
        {
            if (string.IsNullOrEmpty(filepath))
                return;
            string Sitedir = BaseDir;//网站根目录
            filepath = Sitedir + filepath;
            filepath = filepath.Replace("/", @"\").Replace(@"\\", @"\");
            if (File.Exists(filepath))
            {
                try
                {
                    File.Delete(filepath);
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
        }
        /// <summary>
        /// 删除指定目录的所有文件和子目录
        /// </summary>
        /// <param name="targetDir">操作目录</param>
        /// <param name="delSubDir">如果为true,包含对子目录的操作</param>
        public static void DeleteFiles(string targetDir, bool delSubDir)
        {
            try
            {
                foreach (string fileName in Directory.GetFiles(targetDir))
                {
                    File.SetAttributes(fileName, FileAttributes.Normal);
                    File.Delete(fileName);
                }
                if (delSubDir)
                {
                    DirectoryInfo dir = new DirectoryInfo(targetDir);
                    foreach (DirectoryInfo subDi in dir.GetDirectories())
                    {
                        DeleteFiles(subDi.FullName, true);
                        subDi.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// <summary>
        /// 创建指定目录
        /// </summary>
        /// <param name="targetDir"></param>
        public static void CreateDirectory(string targetDir)
        {
            DirectoryInfo dir = new DirectoryInfo(targetDir);
            if (!dir.Exists)
                dir.Create();
        }

        /// <summary>
        /// 建立子目录
        /// </summary>
        /// <param name="targetDir">目录路径</param>
        /// <param name="subDirName">子目录名称</param>
        public static void CreateDirectory(string parentDir, string subDirName)
        {
            CreateDirectory(parentDir + PATH_SPLIT_CHAR + subDirName);
        }

        /// <summary>
        /// 删除指定目录
        /// </summary>
        /// <param name="targetDir">目录路径</param>
        public static void DeleteDirectory(string targetDir)
        {
            if (string.IsNullOrEmpty(targetDir))
                return;
            string Sitedir = BaseDir;//网站根目录
            targetDir = Sitedir + targetDir;
            targetDir = targetDir.Replace("/", @"\").Replace(@"\\", @"\");
            DirectoryInfo dirInfo = new DirectoryInfo(targetDir);
            if (dirInfo.Exists)
            {
                DeleteFiles(targetDir, true);
                dirInfo.Delete(true);
            }
        }

        /// <summary>
        /// 删除指定目录的所有子目录,不包括对当前目录文件的删除
        /// </summary>
        /// <param name="targetDir">目录路径</param>
        public static void DeleteSubDirectory(string targetDir)
        {
            string Sitedir = BaseDir;//网站根目录
            targetDir = Sitedir +@"\"+ targetDir; 
            foreach (string subDir in Directory.GetDirectories(targetDir))
            {
                DeleteDirectory(subDir);
            }
        }

        /// <summary>
        /// 将指定目录下的子目录和文件生成xml文档
        /// </summary>
        /// <param name="targetDir">根目录</param>
        /// <returns>返回XmlDocument对象</returns>
        public static XmlDocument CreateXml(string targetDir)
        {
            XmlDocument myDocument = new XmlDocument();
            XmlDeclaration declaration = myDocument.CreateXmlDeclaration("1.0", "utf-8", null);
            myDocument.AppendChild(declaration);
            XmlElement rootElement = myDocument.CreateElement(targetDir.Substring(targetDir.LastIndexOf(PATH_SPLIT_CHAR) + 1));
            myDocument.AppendChild(rootElement);
            foreach (string fileName in Directory.GetFiles(targetDir))
            {
                XmlElement childElement = myDocument.CreateElement("File");
                childElement.InnerText = fileName.Substring(fileName.LastIndexOf(PATH_SPLIT_CHAR) + 1);
                rootElement.AppendChild(childElement);
            }
            foreach (string directory in Directory.GetDirectories(targetDir))
            {
                XmlElement childElement = myDocument.CreateElement("Directory");
                childElement.SetAttribute("Name", directory.Substring(directory.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                rootElement.AppendChild(childElement);
                CreateBranch(directory, childElement, myDocument);
            }
            return myDocument;
        }

        /// <summary>
        /// 获取指定目录大小
        /// </summary>
        /// <param name="dirPath"></param>
        /// <returns></returns>
        public static long GetDirectoryLength(string dirPath)
        {
            string Sitedir = BaseDir;//网站根目录
            dirPath = Sitedir + dirPath;
            dirPath = dirPath.Replace("/", @"\");
            //判断给定的路径是否存在,如果不存在则退出
            if (!Directory.Exists(dirPath))
                return 0;
            long len = 0;
            try
            {
                //定义一个DirectoryInfo对象
                DirectoryInfo di = new DirectoryInfo(dirPath);

                //通过GetFiles方法,获取di目录中的所有文件的大小
                foreach (FileInfo fi in di.GetFiles())
                {
                    len += fi.Length;
                }
                //获取di中所有的文件夹,并存到一个新的对象数组中,以进行递归
                DirectoryInfo[] dis = di.GetDirectories();
                if (dis.Length > 0)
                {
                    for (int i = 0; i < dis.Length; i++)
                    {
                        len += GetDirectoryLength(dis[i].FullName);
                    }
                }
                return len;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// <summary>
        /// 获取网站根目录
        /// </summary>
        /// <returns></returns>
        public static string GetBaseDir()
        {
            return BaseDir;//网站根目录
        }
        /// <summary>
        /// 生成Xml分支
        /// </summary>
        /// <param name="targetDir">子目录</param>
        /// <param name="xmlNode">父目录XmlDocument</param>
        /// <param name="myDocument">XmlDocument对象</param>
        private static void CreateBranch(string targetDir, XmlElement xmlNode, XmlDocument myDocument)
        {
            foreach (string fileName in Directory.GetFiles(targetDir))
            {
                XmlElement childElement = myDocument.CreateElement("File");
                childElement.InnerText = fileName.Substring(fileName.LastIndexOf(PATH_SPLIT_CHAR) + 1);
                xmlNode.AppendChild(childElement);
            }
            foreach (string directory in Directory.GetDirectories(targetDir))
            {
                XmlElement childElement = myDocument.CreateElement("Directory");
                childElement.SetAttribute("Name", directory.Substring(directory.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                xmlNode.AppendChild(childElement);
                CreateBranch(directory, childElement, myDocument);
            }
        }
    }
}
